import fetch from 'isomorphic-unfetch'
import Layout from '../../components/MyLayout'
import {useRouter} from 'next/router';

const Post = props => {
  const router = useRouter();

  if(router.isFallback){
    console.log('isFallback');
    return <div>Loading...</div>;
  }

  return (
    <Layout>
      <h1>{props.show.name}</h1>
      <p>{props.show.summary.replace(/<[/]?[pb]>/g, '')}</p>
      <img src={props.show.image.medium} />
    </Layout>
  )
};

export async function getStaticPaths() {
  console.log('---blogdetail---getStaticPaths---');
  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
  const data = await res.json();
  const shows = data.map(entry => entry.show);
  const paths = [];
  shows.forEach(show => {
    paths.push({params: { id: String(show.id) }})
  });
  console.log('paths:', paths);
  return {
    paths: paths,
    fallback: true
  }
}

export async function getStaticProps (context) {
  console.log('---blogdetail---getStaticProps---');
  const {id} = context.params;
  const res = await fetch(`https://api.tvmaze.com/shows/${id}`);
  const show = await res.json();
  console.log(`Fetched show: ${show.name}`);
  return {
    props: {
      show
    }
  }
}

export default Post
